import CryptoJS from 'crypto-js'

const cryptoUtils = {
	async encryptParams(params) {
		const plaintext = JSON.stringify(params)
		console.log(plaintext)
		const encryptionKey = 'G4uasIFz4Gy7trW9'

		// 发送请求获取随机数
		const ivStr = await this.getRandomIV()
		const iv = CryptoJS.enc.Hex.parse(ivStr)

		const encrypted = CryptoJS.AES.encrypt(
			plaintext,
			CryptoJS.enc.Utf8.parse(encryptionKey), {
				iv: iv,
				mode: CryptoJS.mode.CBC,
				padding: CryptoJS.pad.Pkcs7
			}
		)

		const ciphertext = encrypted.toString()

		const requestData = {
			ciphertext,
			ivStr
		}
		console.log(JSON.stringify(requestData), '333331111')
		return JSON.stringify(requestData)
	},
	

	getRandomIV() {
		return new Promise((resolve, reject) => {
			// 在这里发送请求获取随机数
			wx.request({
				url: 'http://192.168.11.101:81/saas-platform/public/index.php/api/RandomOffset/generate',
				// url: this.$https.baseUrl + "common/getRandomIV",
				success: (res) => {
					resolve(res.data.data.offset)
				},
				fail: (err) => {
					reject(err)
				}
			})
		})
	}
}

export default cryptoUtils